﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace DBSln
{
    public abstract class DBHelper
    {
        public abstract List<string> GetTableNames();

        public abstract List<string> GetAllColumnNames(string tableName);

        public virtual bool TabExists(string tableName)
        {
            var lstTables = GetTableNames().Select(t => t.ToLower());
            return lstTables.Contains(tableName.ToLower());
        }

        public virtual bool Exists(string strSql, params IDataParameter[] cmdParms)
        {
            object obj = GetSingle<object>(strSql, 0, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public abstract T GetSingle<T>(string strSql, int Times = 30, params IDataParameter[] cmdParms);

        public abstract DataRow QueryRow(string strSql, int Times = 30, params IDataParameter[] cmdParms);

        public abstract DataTable QueryTable(string strSql, int Times = 30, params IDataParameter[] cmdParms);

        public abstract DataSet QueryDataSet(string SQLString, int Times = 30, params IDataParameter[] cmdParms);


        protected void PrepareCommand(IDbCommand cmd, IDbConnection conn, IDbTransaction trans, string cmdText, IDataParameter[] cmdParms, int Times = 30)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (Times > 0)//（以秒为单位）。默认为 30 秒
            {
                cmd.CommandTimeout = Times;
            }
            if (cmdParms != null && cmdParms.Length > 0)
            {
                foreach (IDataParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput
                        || parameter.Direction == ParameterDirection.Input)
                        && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
    }
}
